package com.cms.action;

import java.io.IOException;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.List;

import org.apache.log4j.Logger;

import com.action.DefaultAction;
import com.cms.model.Channel;
import com.cms.model.ChannelTerraceInfo;
import com.cms.model.TerraceInfo;
import com.cms.service.ChannelService;
import com.cms.service.ChannelServiceImpl;
import com.cms.service.TerraceInfoService;
import com.cms.service.TerraceInfoServiceImpl;
import com.model.Admin;

public class ChannelAction extends DefaultAction {

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	private Logger logger;
	private ChannelService service = new ChannelServiceImpl();
	private TerraceInfoService terraceservice = new TerraceInfoServiceImpl();
	private String type;
	private List<Channel> list;
	private List<ChannelTerraceInfo> terracelist;
	private List<TerraceInfo> terraceNameList;
	private Channel model;
	private String msg;
	private String txt_keyword;
	// 平台id
	private String terraceIds;
	// 平台的信息：平台的名称和分成类型
	private String terraceInfo;
	// 渠道平台的关联
	private List<ChannelTerraceInfo> channelTerraceInfos;
	ChannelTerraceInfo t = new ChannelTerraceInfo();

	public ChannelAction() {
		logger = Logger.getLogger(this.getClass());
	}

	public String execute() {
		return SUCCESS;
	}

	public String list() {
		Admin admin = getAdmin();
		if(!"true".equals(admin.getIsAdmin())){
			list = service.getChannelsByAdmin(admin);
		}else{
			list = service.getChannels(txt_keyword);
		}
		//取平台名称和分成类型		
		List<ChannelTerraceInfo> l = service.getChannelTerraceInfos();
		for (Channel channel : list) {
			channel.setTerraceInfo("");
			for (ChannelTerraceInfo c : l) {
				if (c.getChannelId() != channel.getId()) continue;
				
				if (channel.getTerraceInfo().length() > 0  && c.getRelevanceid().length()>0 && c.getGlremark().length()>0) {
					channel.setTerraceInfo(channel.getTerraceInfo() + ",");
				}
				if(c.getRelevanceid()!=null && c.getRelevanceid().length()>0 && c.getGlremark() !=null && c.getGlremark().length()>0){
					channel.setTerraceInfo(channel.getTerraceInfo() + c.getOperatorsName() + "(" + c.getDividetype() + ")");
				}
			}
		}
		return SUCCESS;
	}

	public String show() {
		if (msg.equals("update")) {			
			model = service.getChannel(model.getId());
			terraceNameList = terraceservice.getQuelyTerraceNames();
			// 根据渠道ID查看渠道平台关联信息
			terraceIds = ",";
			terracelist = service.getBychannelId(model.getId());
			for (ChannelTerraceInfo e : terracelist) {
				if (e.getRelevanceid() != null
						&& e.getRelevanceid().length() > 0)
					terraceIds += e.getTerraceId() + ",";
			}
			channelTerraceInfos = new ArrayList<ChannelTerraceInfo>();
		} else {
			model = new Channel();
			model.setId(-1);
			terraceNameList = terraceservice.getQuelyTerraceNames();
			// 根据平台id分配渠道平台的ID
			terracelist = new ArrayList<ChannelTerraceInfo>();
			for (TerraceInfo terrace : terraceNameList) {
				ChannelTerraceInfo tmp = new ChannelTerraceInfo();
				tmp.setTerraceId(terrace.getId());
				tmp.setId(-1);
				tmp.setOperatorsName(terrace.getOperatorsName());
				terracelist.add(tmp);
			}
			terraceIds = ",";
			channelTerraceInfos = new ArrayList<ChannelTerraceInfo>();
		}

		return SUCCESS;
	}

	public ChannelTerraceInfo getChannelTerraceInfo(Channel channel,
			TerraceInfo terrace) {
		for (ChannelTerraceInfo e : channelTerraceInfos) {
			if (e.getChannelId() == channel.getId()
					&& e.getTerraceId() == terrace.getId())
				return e;
		}
		return null;
	}

	/**
	 * 
	 * @return
	 */
	public String save() {
		txt_keyword="";
		if (msg.equals("insert")) {
			List<ChannelTerraceInfo> list = new ArrayList<ChannelTerraceInfo>();
			if (channelTerraceInfos != null && ckb_province != null) {
				for (ChannelTerraceInfo e : channelTerraceInfos) {
					for (int n = 0; n < ckb_province.length; n++) {
						if (e.getTerraceId() == ckb_province[n]) {
							list.add(e);
							continue;
						}
					}
				}
			}
			if (service.insertChannelTerrace(model, list)) {
				msg = "渠道管理：添加渠道成功！！";
			} else {
				msg = "渠道管理：对不起，添加渠道可能存在问题，请稍候重试一下！！";
			}
		} else if (msg.equals("update")) {
			List<ChannelTerraceInfo> list = new ArrayList<ChannelTerraceInfo>();
			if (channelTerraceInfos != null && ckb_province != null) {
				for (ChannelTerraceInfo e : channelTerraceInfos) {
					for (int n = 0; n < ckb_province.length; n++) {
						if (e.getTerraceId() == ckb_province[n]) {
							list.add(e);
							continue;
						}
					}
				}
			}
			if (service.updateChannelTerrace(model, list)) {
				msg = "渠道管理：更新渠道成功！！";
			} else {
				msg = "渠道管理：对不起，更新渠道可能存在问题，请稍候重试一下！！";
			}
		} else if (msg.equals("del")) {
			if (service.deleteChannel1(model)) {
				msg = "渠道管理：删除渠道成功！！";
			} else {
				msg = "渠道管理：对不起，删除渠道可能存在问题，请稍候重试一下！！";
			}
		}
		return SUCCESS;
	}

	public String chkchannelname(){
	    getResponse().setCharacterEncoding("utf-8");  
        PrintWriter pw=null;  
        try {  
        	String name = new String(model.getName().getBytes("ISO8859-1"),"UTF-8");
            pw = getResponse().getWriter();  
            List<Channel> l = service.getChannels();
            for (Channel channel : l) {
				if(channel.getName().equals(name)){
					pw.write("1"); 
					break;
				}
			}
        } catch (IOException e) {  
            System.out.println(e.getMessage());
        }  
        pw.flush();  
        pw.close();  
		return null;
	}
	public String getMsg() {
		return msg;
	}

	public void setMsg(String msg) {
		this.msg = msg;
	}

	public String getType() {
		return type;
	}

	public void setType(String type) {
		this.type = type;
	}

	public List<Channel> getList() {
		return list;
	}

	public void setList(List<Channel> list) {
		this.list = list;
	}

	public Channel getModel() {
		return model;
	}

	public void setModel(Channel model) {
		this.model = model;
	}

	public String getTxt_keyword() {
		return txt_keyword;
	}

	public void setTxt_keyword(String txtKeyword) {
		txt_keyword = txtKeyword;
	}

	public List<ChannelTerraceInfo> getTerracelist() {
		return terracelist;
	}

	public void setTerracelist(List<ChannelTerraceInfo> terracelist) {
		this.terracelist = terracelist;
	}

	public List<TerraceInfo> getTerraceNameList() {
		return terraceNameList;
	}

	public void setTerraceNameList(List<TerraceInfo> terraceNameList) {
		this.terraceNameList = terraceNameList;
	}

	public List<ChannelTerraceInfo> getChannelTerraceInfos() {
		return channelTerraceInfos;
	}

	public void setChannelTerraceInfos(
			List<ChannelTerraceInfo> channelTerraceInfos) {
		this.channelTerraceInfos = channelTerraceInfos;
	}

	public String getTerraceIds() {
		return terraceIds;
	}

	public void setTerraceIds(String terraceIds) {
		this.terraceIds = terraceIds;
	}

	private int[] ckb_province;

	public int[] getCkb_province() {
		return ckb_province;
	}

	public void setCkb_province(int[] ckb_province) {
		this.ckb_province = ckb_province;
	}

	public String getTerraceInfo() {
		return terraceInfo;
	}

	public void setTerraceInfo(String terraceInfo) {
		this.terraceInfo = terraceInfo;
	}
}
